<template>
  <div class="inner">
    <PageTitle title="装箱单" />
    <div class="ibody" v-if="loaded">
      <div class="ib-input">
        <div
          class="scan-logo"
          v-if="!boxData || boxData.orderfills.length === 0"
        >
          <el-image :src="szxPng" class="fenjian-d" mode="aspectFit" />
          <el-image :src="scanQpng" class="scan-q wh-flash" mode="aspectFit" />
        </div>
        <div class="input">
          <el-row :gutter="20">
            <el-col :span="18">
              <el-input
                placeholder="请输入包裹单号"
                v-model="orderfillNo"
                size="large"
              />
            </el-col>
            <el-col :span="6">
              <div
                class="wh-btn primary"
                @click="confirmGetPackageDetail"
                size="large"
              >
                确定
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <div class="drugs mt20" v-if="boxData && boxData.orderfills.length > 0">
        <div class="d-table-wrap">
          <el-table
            :data="boxData.orderfills"
            style="width: 100%"
            row-class-name="table-normal-row"
            header-row-class-name="table-header-row"
          >
            <el-table-column prop="orderfillId" label="编号" />
            <el-table-column prop="orderfillNo" label="包裹单号" />
            <el-table-column prop="shippingAddress" label="配送点" />
            <el-table-column label="操作">
              <template #default="scope">
                <div
                  v-if="boxData.status !== '已发货'"
                  class="wh-btn danger border-solid"
                  @click="deletePackage(scope.row.orderfillId)"
                >
                  删除
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="productor" v-if="boxData.status === '已发货'">
          <el-row class="p-row">
            <el-col :span="12">
              <div class="label">包裹数量</div>
              <div class="value">{{ boxData.orderfills.length }}</div>
            </el-col>
            <el-col :span="12">
              <div class="label">配送商</div>
              <div class="value">{{ boxData.distributorName }}</div>
            </el-col>
          </el-row>
          <el-row class="p-row">
            <el-col :span="12">
              <div class="label">出库人</div>
              <div class="value">{{ boxData.outWarehousePerson }}</div>
            </el-col>
            <el-col :span="12">
              <div class="label">出库时间</div>
              <div class="value">{{ boxData.outWarehouseTime }}</div>
            </el-col>
          </el-row>
        </div>
        <div class="productor" v-else>
          <div class="num">已装数量：{{ boxData.orderfills.length }}</div>
          <div class="apply">
            <div class="label">配送商</div>
            <div class="value">
              <div
                :class="[
                  'wh-btn',
                  'border-solid',
                  boxData.distributorId === item.id ? 'active' : ''
                ]"
                v-for="(item, index) in distributorList"
                :key="index"
                @click="choseDistributor(item.id)"
              >
                {{ item.name }}
              </div>
            </div>
          </div>
        </div>

        <div class="btn-group" v-if="boxData.status !== '已发货'">
          <div class="wh-btn large border-solid primary" @click="goOutbound">
            出库
          </div>
          <div class="wh-btn large border-solid right" @click="saveOutbound">
            暂存装箱单
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import PageTitle from "@/components/PageTitle.vue";
import { ref, onMounted, onUnmounted, markRaw } from "vue";
import { ElMessage } from "element-plus";
import {
  getOutboundDetailApi,
  getDistributorsApi,
  submitOutboundApi
} from "@/api/outbound";
import { getPackageDetailApi } from "@/api/package";
import { useRouter, useRoute } from "vue-router";
import { useUserStoreHook } from "@/store/modules/user";
import { Warning } from "@element-plus/icons-vue";
import { debounce } from "@/utils/tools";
import szxPng from "@/assets/img/szx.png";
import scanQpng from "@/assets/img/scanQ.png";
import { myDialog } from "@/components/myDialog";

const userStore = useUserStoreHook();
const warehouseId = userStore.userInfo.warehouseId;
const userId = userStore.userInfo.user;
const router = useRouter();
const route = useRoute();
const packageId = ref("");
const editType = ref("new");
const boxData = ref({
  distributorId: "",
  orderfills: [],
  status: "",
  outWarehousePerson: "",
  outWarehouseTime: "",
  distributorName: ""
});
const deleteOrderfillIds = ref([]);

const distributorList = ref([]);
const orderfillNo = ref("");
const loaded = ref(false);

// 0 还没有扫码包裹单
const status = ref(0);

function deletePackage(orderfillId) {
  const tempOrderFills = boxData.value.orderfills.filter(item => {
    return item.orderfillId !== orderfillId;
  });
  boxData.value.orderfills = tempOrderFills;
  if (!deleteOrderfillIds.value.includes(orderfillId)) {
    deleteOrderfillIds.value.push(orderfillId);
  }
}

async function getOutboundDetail(packageId) {
  const data = await getOutboundDetailApi(packageId);
  console.log("data:", data);
  boxData.value = data;
  loaded.value = true;
}

function choseDistributor(id) {
  boxData.value.distributorId = id;
}

async function goOutbound() {
  if (
    boxData.value.distributorId === undefined ||
    boxData.value.distributorId === ""
  ) {
    myDialog.warning({
      message: "请选择配送商"
    });
    return;
  }
  myDialog.warning({
    message: `本次出库包裹 ${boxData.value.orderfills.length} 个，是否确认？`,
    showCancel: true,
    confirmFn: async () => {
      const outboundType = {
        userId: userId,
        packageId: packageId.value,
        orderfillIds: boxData.value.orderfills
          .map(item => {
            return item.orderfillId;
          })
          .join(","),
        deleteOrderfillIds:
          editType.value === "new" ? "" : deleteOrderfillIds.value.join(","),
        distributorId: boxData.value.distributorId,
        type: 2 // 操作类型 1=保存 2=出库
      };
      await submitOutboundApi(outboundType);
      ElMessage({
        type: "success",
        message: "出库成功"
      });
      setTimeout(() => {
        router.push({ path: "/box/list" });
      }, 500);
    }
  });
  // ElMessageBox.confirm(
  //   `本次出库包裹 ${boxData.value.orderfills.length} 个，是否确认？`,
  //   "提示",
  //   {
  //     confirmButtonText: "确定",
  //     cancelButtonText: "取消",
  //     type: "warning"
  //   }
  // )
  //   .then(async () => {
  //     const outboundType = {
  //       userId: userId,
  //       packageId: packageId.value,
  //       orderfillIds: boxData.value.orderfills
  //         .map(item => {
  //           return item.orderfillId;
  //         })
  //         .join(","),
  //       deleteOrderfillIds:
  //         editType.value === "new" ? "" : deleteOrderfillIds.value.join(","),
  //       distributorId: boxData.value.distributorId,
  //       type: 2 // 操作类型 1=保存 2=出库
  //     };
  //     await submitOutboundApi(outboundType);
  //     ElMessage({
  //       type: "success",
  //       message: "出库成功"
  //     });
  //     setTimeout(() => {
  //       router.push({ path: "/box/list" });
  //     }, 500);
  //   })
  //   .catch(() => {
  //     console.log("取消");
  //   });
}

async function saveOutbound() {
  if (
    boxData.value.distributorId === undefined ||
    boxData.value.distributorId === ""
  ) {
    myDialog.warning({
      message: "请选择配送商"
    });
    return;
  }
  if (boxData.value.orderfills.length > 0) {
    const outboundType = {
      userId: userId,
      orderfillIds: boxData.value.orderfills
        .map(item => {
          return item.orderfillId;
        })
        .join(","),
      distributorId: boxData.value.distributorId,
      type: 1 // 操作类型 1=保存 2=出库
    };
    try {
      await submitOutboundApi(outboundType);
      ElMessage({
        type: "success",
        message: "保存成功"
      });
      router.push({ path: "/box/list" });
    } catch (error) {
      console.log("error");
      // ElMessage({
      //   type: "error",
      //   message: "服务器出错，请稍后再试"
      // });
    }
  } else {
    myDialog.warning({
      message: "包裹数量不能为空"
    });
    return;
  }
}

// 将包裹添加到装箱单
const pushBaoGuoToBox = debounce(
  async function pushBaoGuoToBox(tempOrderfillNo) {
    if (tempOrderfillNo) {
      // 查询包裹详情

      const hadInput = boxData.value.orderfills.find(item => {
        return item.orderfillNo === tempOrderfillNo;
      });
      if (!hadInput) {
        const baoGuoData = await getPackageDetailApi(tempOrderfillNo);
        if (baoGuoData.status !== "待出库") {
          myDialog.warning({
            message:
              "只有待出库的包裹才能创建装箱单，当前包裹状态：" +
              baoGuoData.status
          });
          return;
        }
        boxData.value.orderfills.push(baoGuoData);
        status.value = 1;
        orderfillNo.value = "";
      } else {
        myDialog.warning({
          message: "当前包裹已经扫码过，请核对"
        });
      }
    }
  },
  500,
  true
);

function confirmGetPackageDetail() {
  console.log("confirmGetPackageDetail orderfillNo.value:", orderfillNo.value);
  pushBaoGuoToBox(orderfillNo.value);
}
// 扫码枪事件
let scanInputNumber = "";
let keyLastTime = 0;
function enterEvent(orderfillNo) {
  console.log("enterEvent orderfillNo:", orderfillNo);
  status.value = 1;
  pushBaoGuoToBox(orderfillNo);
}

function keyDownEvent(event) {
  let gap = 0;
  if (keyLastTime) {
    gap = new Date().getTime() - keyLastTime;
    // 大于50毫秒，则判定为人输入
    if (gap > 50) {
      gap = 0;
      scanInputNumber = "";
    }
  }
  keyLastTime = new Date().getTime();
  if (gap < 50) {
    const theEvent = event || window.event;
    const code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code !== 13 && theEvent.key.length === 1) {
      scanInputNumber += theEvent.key;
    }

    if (code === 13) {
      scanInputNumber = scanInputNumber.replace(/\D*/, "");
      enterEvent(scanInputNumber);
      scanInputNumber = "";
      keyLastTime = 0;
    }
  }
}
async function init() {
  boxData.value = {
    distributorId: "",
    orderfills: [],
    status: "",
    outWarehousePerson: "",
    outWarehouseTime: "",
    distributorName: ""
  };
  orderfillNo.value = "";
  deleteOrderfillIds.value = [];
  packageId.value = route.query.packageId as string;
  editType.value = route.query.editType as string;

  distributorList.value = await getDistributorsApi(warehouseId);
  if (packageId.value && editType.value === "edit") {
    getOutboundDetail(packageId.value);
  } else {
    loaded.value = true;
  }
}
onMounted(async () => {
  init();
  document.addEventListener("keydown", keyDownEvent);
});
onUnmounted(() => {
  document.removeEventListener("keydown", keyDownEvent);
});
</script>
<style lang="scss" scoped>
$drugItemWidth: 120px;
.ibody {
  position: relative;
  .ib-input {
    .scan-logo {
      margin: auto;
      margin-top: 40px;
      width: 312px;
      height: 308px;
      position: relative;
      border: 1px dashed #ddd;
      .scan-q {
        position: absolute;
        right: 68px;
        top: 168px;

        width: 174px;
        height: 148px;
      }
    }
    .input {
      margin: auto;
      width: 400px;
      margin-top: 30px;
      .el-col {
        display: flex;
        align-items: center;
      }
    }
  }

  .drugs {
    width: 100%;
    height: calc(100vh - 208px);
    .d-table-wrap {
      margin-top: 20px;
      padding: 20px;
      background-color: white;
      border-radius: 10px;
    }
    .productor {
      margin-top: 20px;
      padding: 20px;
      background-color: white;
      border-radius: 10px;
      padding-bottom: 40px;
      .num {
        height: 50px;
        line-height: 50px;
        border-bottom: 1px dashed #d8d8d8;
      }
      .apply {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        margin-top: 20px;
        .label {
          text-align: left;
        }
      }
      .p-row {
        height: 50px;
        line-height: 50px;
        border-bottom: 1px dashed #d8d8d8;
        .el-col {
          display: flex;
          align-items: center;
          justify-content: flex-start;
        }
      }
      .label {
        font-size: 18px;
        font-weight: bold;
        text-align: left;
        color: #b5b5c3;
        margin-right: 20px;
        width: 100px;
        text-align: right;
      }
      .value {
        display: flex;
        align-items: center;
        justify-content: flex-start;
      }
    }
    .btn-group {
      margin-top: 20px;
      display: flex;
      justify-content: center;
      .wh-btn {
        &.right {
          margin-right: 0px;
          display: block;
          position: absolute;
          right: 20px;
        }
      }
    }
  }
}
</style>
